import { defineStore } from 'pinia';
import { removeToken, toLogin } from '@/utils';
import { usePermissionStore, useTabStore } from '@/store';
import { resetRouter } from '@/router';

interface UserInfo {
  id?: string;
  name?: string;
  avatar?: string; // 头像地址
  role?: Array<string>;
}

export const useUserStore = defineStore('user', {
  state() {
    return {
      userInfo: <UserInfo>{},
    };
  },
  getters: {
    userId(): string {
      return this.userInfo.id || '';
    },
    name(): string {
      return this.userInfo.name || '';
    },
    avatar(): string {
      return import.meta.env.VITE_BASE_API + this.userInfo.avatar || '';
    },
    role(): Array<string> {
      return this.userInfo.role || [];
    },
  },
  actions: {
    async getUserInfo() {
      // 首先从 localStorage 获取并解析 userinfo
      const userinfoStr = localStorage.getItem('userInfo');
      const userinfo = userinfoStr ? JSON.parse(userinfoStr) : {};
      console.log(userinfo);
      
      // 设置 userInfo 对象
      this.userInfo = {
        id: userinfo.username || '',
        name: userinfo.nickname || '',
        avatar: userinfo.img || '', // 头像地址
        role: this.getUserRole(userinfo.type),
      };
      console.log(this.userInfo, '角色信息');
      
    },
    // 添加一个单独的方法来处理角色判断
    getUserRole(type: number) {
      console.log(type);
      
      switch (type) {
        case 0:
          return ['admin'];
        case 1:
          return ['teacher'];
        case 2:
          return ['student'];
        default:
          return ['partner'];
      }
    },
    async logout() {
      const { resetTabs } = useTabStore();
      const { resetPermission } = usePermissionStore();
      removeToken();
      resetPermission();
      resetTabs();
      resetRouter();
      this.$reset();
      toLogin();
    },
    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo };
    },
  },
});
